import { Fetch, FetchAPI } from '../util/Fetch'

export interface UserInfo {
    id: string;
    name: string;
    stared?: boolean;
    token?: string;
}
export interface StarResp {
    count: number;
    type: string;
}
export type UnreadCount = Record<'infos' | 'messages' | 'referer' | 'total', number>

export interface AuthorInfo {
    name: string;
    nickname: string;
    username: string;
}
export interface EventInfo {
    author: AuthorInfo;
    created_at: string;
    updated_at: string;
    title: string;
}

let csrf_token: string
export const api_gitee: {
    user_info: FetchAPI<never, UserInfo>;
    /** star */
    star: FetchAPI<never, StarResp>;
    /** 取消star */
    unstar: FetchAPI<never, StarResp>;
    /** 获取未读信息条数 */
    unread_count: () => Promise<UnreadCount>;
    /** 获取最近事件 */
    events: FetchAPI<never, {events: EventInfo[]}>
} = {
    user_info: () => Fetch<null, string>('https://gitee.com/f2e-server/f2e-crx-creator', null, {}, 'txt').then((doc = '') => {
        const flag = `<div class='gitee-nav__info-box'>`
        const flag_stared = `<span class='basic buttons star-container stared ui'>`
        const index = doc.indexOf(flag)
        const stared = doc.includes(flag_stared)
        const [, token] = doc.match(/<meta name="csrf-token" content="([^"]+)/) || []
        csrf_token = token
        if (index != -1) {
            const [, id, name] = doc.substring(index + flag.length).match(/<a href="\/([^"]+)">([^\\/]+)<\/a>/) || []
            return {
                code: 200,
                data: { id, name, stared, token },
            }
        }
        return { code: -1 }
    }),
    star: () => Fetch('https://gitee.com/f2e-server/f2e-crx-creator/star', {}, { headers: { 'X-CSRF-Token': csrf_token } }),
    unstar: () => Fetch('https://gitee.com/f2e-server/f2e-crx-creator/unstar', {}, { headers: { 'X-CSRF-Token': csrf_token } }),
    unread_count: () => Fetch('https://gitee.com/notifications/unread_count'),
    events: () => Fetch('https://gitee.com/f2e-server/f2e-crx-creator/events.json'),
}